package com.mq.common;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author zhanghaidong
 * @version v1.0
 * @description
 * @date 2019/8/16
 */
public class MqConnectionUtils {

    private static Connection CONNECTION;

    static {
        try {
            CONNECTION = getConn();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }


    /**
     * 方式一
     *    ConnectionFactory factory = new ConnectionFactory();
     *    factory.setUri("amqp://userName:password@hostName:portNumber/virtualHost");
     *    Connection conn = factory.newConnection();
     */
    private static Connection getConn() throws IOException, TimeoutException {
        System.out.println("--------------------获取Tcp连接-----------------------");
        /**
         * 方式二
         */
        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setUsername("zhanghaidong");
        connectionFactory.setPassword("mqzhd123");
        connectionFactory.setVirtualHost("/");
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);

        return connectionFactory.newConnection();
    }

    public static Connection getConnection() {
        return CONNECTION;
    }
}
